package com.baixiaowen.xiaoaointerview.并发基础篇;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 自定义实现 Semaphore
 *
 * @author Baixiaowen
 */
public class CustomSemaphore {

    static class Semaphore extends AbstractQueuedSynchronizer {
        public Semaphore(int permits) {
            // 设置 Semaphore 初始的状态值
            setState(permits);
        }

        /**
         * 多线程共享获取锁
         * @param arg
         * @return -1失败 负数即代表失败
         */
        @Override
        protected int tryAcquireShared(int arg) {
            // 代表现在还允许多少线程进入临界区
            int available = getState();
            if (available == 0) {
                return -1;
            }
            int left = available - 1;
            if (compareAndSetState(available, left)) {
                return left;
            }
            return -1;
        }

        /**
         * 多线程共享释放锁
         * @param arg
         * @return -1失败 负数即代表失败
         */
        @Override
        protected boolean tryReleaseShared(int arg) {
            int available = getState();
            return compareAndSetState(available, available + 1);
        }
    }

    public static void main(String[] args) {
//        Semaphore semaphore = new Semaphore(3);
        java.util.concurrent.Semaphore semaphore1 = new java.util.concurrent.Semaphore(3);

        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                try {
                    semaphore1.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                semaphore.acquireShared(0);
                try {
                    System.err.println("go");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                semaphore1.release();
//                semaphore.releaseShared(0);

            }).start();
        }
    }

}
